package com.zxj.databaseframework.db;

import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.zxj.databaseframework.App;

/**
 * Created by zuo on 2018/3/8.
 */

public class BaseDaoFactory {
    private static final BaseDaoFactory instance = new BaseDaoFactory();
    private SQLiteDatabase mSQLiteDatabase;
    private String sqliteDatabasePath;

    public static BaseDaoFactory getInstance(){
        return instance;
    }

    private BaseDaoFactory(){
        if(isExistSDCard()){
            sqliteDatabasePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/user.db";
        }else {
            sqliteDatabasePath = "data/data/"+ App.getInstance().getPackageName()+"/user.db";
        }
        this.mSQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqliteDatabasePath,null);
    }

    /**
     *
     * @param clazz BaseDao及BaseDao的子类
     * @param entityClass Bean对象（User.class）
     * @param <T>
     * @param <M>
     * @return
     */
    public synchronized <T extends BaseDao<M>,M> T getDataHelper(Class<T> clazz,Class<M> entityClass){
        BaseDao baseDao = null;
        try {
            baseDao = clazz.newInstance();
            baseDao.init(mSQLiteDatabase,entityClass);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) baseDao;
    }

    /**
     * SD卡是否存在
     * @return
     */
    private boolean isExistSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
